﻿using System;
using System.Reflection;

namespace KouDai.Core.Service
{
    internal class EventService
    {
        public static EventHandler MakeWeak(EventHandler handler, Action<EventHandler> removeFunc)
        {
            var reference = new WeakReference(handler.Target);
            var method = handler.GetMethodInfo();

            EventHandler newHandler = null;
            newHandler = (sender, e) =>
                {
                    var target = reference.Target;
                    if (target != null)
                    {
                        method.Invoke(target, new object[] { sender, e });
                    }
                    else
                    {
                        //收集
                        removeFunc(newHandler);
                    }
                };
            return newHandler;
        }


        public static EventHandler MakeWeakSimple(EventHandler handler, Action<EventHandler> removeFunc)
        {
            var m_EventHandler = handler;

            EventHandler m_Handler = null;
            m_Handler = (sender, e) =>
                {
                    if (m_EventHandler != null)
                    {
                        m_EventHandler(sender, e);
                        m_EventHandler = null;
                    }

                    if (removeFunc != null)
                    {
                        removeFunc(handler);
                        removeFunc = null;
                    }
                };
            return m_Handler;
        }
    }

}
